package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Optional;

/**
 * checkinService业务层处理
 *
 * @author ruoyi
 * @date 2025-05-23
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private BedMapper bedMapper;


    /**
     * 查询checkin
     *
     * @param id checkin主键
     * @return checkin
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询checkin列表
     *
     * @param checkIn checkin
     * @return checkin
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增checkin
     *
     * @param checkIn checkin
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改checkin
     *
     * @param checkIn checkin
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除checkin
     *
     * @param ids 需要删除的checkin主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除checkin信息
     *
     * @param id checkin主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        log.info("入住办理：{}", dto);
        // 1、判断老人是否已入住
        // 根据身份证号判断
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();//身份证号
        // 根据身份证号查询老人信息
        Elder elderInDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, idCardNo));
        log.info("数据库中的老人信息: {}", elderInDb);
        if (elderInDb != null) {
            if (elderInDb.getStatus() == 1 || elderInDb.getStatus() == 2 || elderInDb.getStatus() == 4) {
                // 已入住
                throw new ServiceException("该老人已入住");
            }
        }
        // 2、更新床位状态
        Long bedId = dto.getCheckInConfigDto().getBedId();//床位id
        int count = bedMapper.insertStatusById(bedId);
        // update bed set status=1 where id=? and status=0  数据库的行锁，解决多线程资源竞争问题
        log.info("更新床位状态: count={}, id={}", count, bedId);
        if (count == 0) {
            //床位被占用了
            throw new ServiceException("该床位已被占用，请选择其它床位");
        }
        // 3、新增或更新老人
        Elder elder = addOrUpdateElder(dto, bedId, elderInDb);
        // 4、新增签约办理
        addContract(dto, elder);
        // 5、新增入住信息
        CheckIn checkIn = addCheckIn(dto, elder);
        // 6、新增入住配置
        addCheckINConfig(dto, checkIn);
    }

    /**
     * 获取入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getDetail(Integer id) {
        // 查询入住表
        CheckInDetailVo vo = new CheckInDetailVo();
        CheckIn checkIn = getById(id);
        // 查询老人表并封装进vo
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        //Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getId, checkIn.getElderId()));
        /*if (elder != null) {
            CheckInElderVo eldervo = BeanUtil.toBean(elder, CheckInElderVo.class);
            //设置老人的年龄
            eldervo.setAge(DateUtil.ageOfNow(elder.getBirthday()));
            //eldervo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
            vo.setCheckInElderVo(eldervo);
        }*/
        Optional.ofNullable(elder).ifPresent(e -> {
            CheckInElderVo elderVo = BeanUtil.toBean(e, CheckInElderVo.class);
            //设置老人的年龄
            elderVo.setAge(IdcardUtil.getAgeByIdCard(e.getIdCardNo()));
            vo.setCheckInElderVo(elderVo);
        });
        // 查询家属信息并封装进vo
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVoList);
        // 查询入住配置并封装进vo
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        System.out.println(checkIn);
        System.out.println(checkInConfig);
        System.out.println(checkInConfigVo);
        vo.setCheckInConfigVo(checkInConfigVo);
        // 查询签约办理并封装进vo
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elder.getId()));
        vo.setContract(contract);
        return vo;
    }

    /**
     * 新增入住配置
     *
     * @param dto
     * @param checkIn
     */
    private void addCheckINConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
        log.info("新增入住配置信息: id={}", checkInConfig.getId());
    }

    /**
     * 新增入住信息
     *
     * @param dto
     * @param elder
     */
    private CheckIn addCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        // 设置紧急联系人信息
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        // checkInMapper.save(checkIn);
        log.info("新增入住信息: id={}", checkIn.getId());
        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param dto
     * @param elder
     */
    private void addContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        // 开始时间与结束时间
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        // 生成合同编号
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        // 设置合同状态
        LocalDateTime now = LocalDateTime.now();
        if (endDate.isBefore(now)) {
            // 合同一创建就已过期，没意义
            throw new ServiceException("结束日期要大于当前系统日期");
        }
        // 状态值与当前系统时间对比
        if (startDate.isBefore(now)) {
            // 开始时间小于当前时间，状态为已生效
            contract.setStatus(1);
        } else {
            // 开始时间大于当前时间，状态为未生效
            contract.setStatus(0);
        }
        contractMapper.insert(contract);
        log.info("新增合同成功,id={}", contract.getId());
    }

    /**
     * 新增或更新老人
     *
     * @param dto
     * @param bedId
     * @param elderInDb
     * @return
     */
    private Elder addOrUpdateElder(CheckInApplyDto dto, Long bedId, Elder elderInDb) {
        Elder elder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        elder.setBedId(bedId);
        elder.setStatus(1);
        elder.setBedNumber(bedMapper.selectBedById(bedId).getBedNumber());
        if (elderInDb == null) {
            // 老人不存在则新增老人信息
            elderMapper.insert(elder);
            log.info("新增老人信息成功,id={}", elder.getId());
        } else {
            elderMapper.updateById(elder);
            log.info("更新老人信息成功,id={}", elder.getId());
        }
        return elder;
    }
}
